﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;

namespace WindowsFormsDemo
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        Process _process;
        bool isFirst = false;

        private void MainForm_Load(object sender, EventArgs e)
        {
            Process[] processs = Process.GetProcessesByName("WpfApp.exe");
            foreach (var item in processs)
            {
                item.Kill();
            }

            //string strPath = this.GetType().Assembly.Location;
            //string baseDir = Path.Combine(strPath.Substring(0, strPath.LastIndexOf("\\")), "");
            string fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "WpfApp.exe");

            if (File.Exists(fileName))
            {
                // 设置消息参数
                string param = "ServerIP=127.0.0.1&Type=2&UserID=xx&CaseID=604dffdd-0f8f-430d-8ca4-1d9714ba7609";
                ProcessStartInfo startInfo = new ProcessStartInfo(fileName);

                startInfo.Arguments = "UploadFile," + param + "," + this.Handle;
                startInfo.UseShellExecute = true;
                startInfo.CreateNoWindow = true;
                startInfo.WorkingDirectory = "";
                startInfo.WindowStyle = ProcessWindowStyle.Hidden;

                _process = Process.Start(startInfo);
                _process.EnableRaisingEvents = true;
                WaitForInputIdle();
                EmbedProcess(_process);
            }
            else
                MessageBox.Show("未找到需要启动的exe文件");
            isFirst = true;
        }

        private void WaitForInputIdle()
        {
            while (_process.MainWindowHandle == IntPtr.Zero)
            {
                _process.Refresh();
                _process.MainWindowHandle.ToInt32();
            }
        }

        /// <summary>
        /// 嵌入程序
        /// </summary>
        private void EmbedProcess(Process process)
        {
            if (process != null && !(process.MainWindowHandle == IntPtr.Zero))
            {
                try
                {
                    // Put it into this form
                    AppContainer.SetParent(process.MainWindowHandle, panel1.Handle);
                    // Remove border and whatnot               
                    AppContainer.SetWindowLong(new HandleRef(this, process.MainWindowHandle));
                    // Move the window to overlay it on this window
                    AppContainer.MoveWindow(_process, panel1);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void MainForm_Resize(object sender, EventArgs e)
        {
            // 设置窗体填充主窗体
            if (isFirst)
                AppContainer.MoveWindow(_process, this);
        }

        public string Prams { get; set; }

        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        private static extern int SendMessage(IntPtr hWnd, int msg, uint wParam, uint lParam);

        // 响应和处理自定义消息
        protected override void DefWndProc(ref System.Windows.Forms.Message m)
        {
            switch (m.Msg)
            {
                case Message.WM_MSG://处理接收到的消息
                    int success = m.WParam.ToInt32();
                    if (success == 0)
                        MessageBox.Show("成功");
                    break;
                default:
                    base.DefWndProc(ref m);
                    break;
            }
        }

        public class Message
        {
            public const int USER = 0x0400;
            public const int WM_MSG = USER + 101;
        }
    }
}
